<script lang="ts" setup>
import type {
  V2NIMTeam,
  V2NIMTeamMember,
} from 'nim-web-sdk-ng/dist/v2/NIM_UNIAPP_SDK/V2NIMTeamService'
import type { MentionedMember } from './message-input.vue'
/** @ 列表组件，用于在群里@ 成员列表 */
import { autorun } from 'mobx'
import Appellation from '../../../components/Appellation.vue'
import Avatar from '../../../components/Avatar.vue'
import Icon from '../../../components/Icon.vue'
import { ALLOW_AT, AT_ALL_ACCOUNT, events } from '../../utils/constants'

import { t } from '../../utils/i18n'

import { V2NIMConst } from '../../utils/nim'
import {
  computed,
  onUnmounted,
  ref,
  withDefaults,
} from '../../utils/transformVue'

const props = withDefaults(
  defineProps<{
    teamId: string
  }>(),
  {},
)

const team = ref<V2NIMTeam>()
const teamMembers = ref<V2NIMTeamMember[]>([])
const teamExt = ref('')

/** 群成员 不包括当前登录用户 */
const teamMembersWithoutSelf = computed(() => {
  return teamMembers.value.filter(
    item => item.accountId !== uni.$UIKitStore.userStore.myUserInfo.accountId,
  )
})

/** 是否是群主 */
const isGroupOwner = computed(() => {
  const myUser = uni.$UIKitStore.userStore.myUserInfo
  return (
    (team.value ? team.value.ownerAccountId : '')
    === (myUser ? myUser.accountId : '')
  )
})

/** 是否是群管理员 */
const isGroupManager = computed(() => {
  const myUser = uni.$UIKitStore.userStore.myUserInfo
  return teamMembers.value
    .filter(
      item =>
        item.memberRole
        === V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_MANAGER,
    )
    .some(member => member.accountId === (myUser ? myUser.accountId : ''))
})

/** 是否允许@ 所有人 */
const allowAtAll = computed(() => {
  let ext: any = {}
  try {
    ext = JSON.parse(teamExt.value || '{}')
  }
  catch (error) {
    //
  }
  if (ext[ALLOW_AT] === 'manager') {
    return isGroupOwner.value || isGroupManager.value
  }
  return true
})

/** 群成员排序 群主 > 管理员 > 成员 */
function sortGroupMembers(members: V2NIMTeamMember[], teamId: string) {
  const owner = members.filter(
    item =>
      item.memberRole
      === V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_OWNER,
  )
  const manager = members
    .filter(
      item =>
        item.memberRole
        === V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_MANAGER,
    )
    .sort((a, b) => a.joinTime - b.joinTime)
  const other = members
    .filter(
      item =>
        ![
          V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_OWNER,
          V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_MANAGER,
        ].includes(item.memberRole),
    )
    .sort((a, b) => a.joinTime - b.joinTime)
  const result = [...owner, ...manager, ...other].map((item) => {
    return {
      ...item,

      name: uni.$UIKitStore.uiStore.getAppellation({
        account: item.accountId,
        teamId,
      }),
    }
  })
  return result
}

/**
 * 群成员点击函数
 */
function handleItemClick(member: V2NIMTeamMember | MentionedMember) {
  const _member: MentionedMember
    = member.accountId === AT_ALL_ACCOUNT
      ? (member as MentionedMember)
      : {
        accountId: member.accountId,
        appellation: uni.$UIKitStore.uiStore.getAppellation({
          account: member.accountId,
          teamId: (member as V2NIMTeamMember).teamId,
          ignoreAlias: true,
        }),
      }
  uni.$emit(events.HANDLE_AIT_MEMBER, _member)
}

function onClosePopup() {
  uni.$emit(events.CLOSE_AIT_POPUP)
}
/** 监听群成员 */
const teamMemberWatch = autorun(() => {
  if (props.teamId) {
    teamMembers.value = sortGroupMembers(
      // @ts-ignore
      uni.$UIKitStore.teamMemberStore.getTeamMember(props.teamId),
      props.teamId,
    )
    // @ts-ignore
    const _team: V2NIMTeam = uni.$UIKitStore.teamStore.teams.get(props.teamId)
    if (team) {
      team.value = _team
      teamExt.value = _team?.serverExtension || ''
    }
  }
})

onUnmounted(() => {
  /** 移除监听 */
  teamMemberWatch()
})
</script>

<template>
  <view class="mention-member-list-wrapper">
    <view class="header">
      <view class="close" @tap="onClosePopup">
        <Icon color="#000" type="icon-jiantou" />
      </view>
      <view class="title">{{ t('chooseMentionText') }}</view>
    </view>
    <view class="member-list-content">
      <view style="display: none">{{ teamExt }}</view>
      <view
        v-if="allowAtAll"
        class="member-item"
        @tap="
          () =>
            handleItemClick({
              accountId: AT_ALL_ACCOUNT,
              appellation: t('teamAll'),
            })
        "
      >
        <Icon :size="42" type="icon-team2" color="#fff" />
        <span class="member-name">
          {{ t('teamAll') }}
        </span>
      </view>
      <view
        v-for="member in teamMembersWithoutSelf"
        :key="member.accountId"
        class="member-item"
        @tap="() => handleItemClick(member)"
      >
        <Avatar :account="member.accountId" />
        <view class="member-name">
          <Appellation
            :account="member.accountId"
            :team-id="member.teamId"
          ></Appellation>
        </view>
        <view
          v-if="
            member.memberRole
              === V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_OWNER
          "
          class="owner"
        >
          {{ t('teamOwner') }}
        </view>
        <view
          v-else-if="
            member.memberRole
              === V2NIMConst.V2NIMTeamMemberRole.V2NIM_TEAM_MEMBER_ROLE_MANAGER
          "
          class="manager"
        >
          {{ t('teamManager') }}
        </view>
      </view>
      <view class="member-item-block"></view>
    </view>
  </view>
</template>

<style scoped lang="scss">
@import '../../styles/common.scss';

.mention-member-list-wrapper {
  z-index: 9999999;
  touch-action: none;
}

.title {
  text-align: center;
  font-weight: 500;
  margin: 0 auto;
}

.header {
  display: flex;
  align-items: center;
  height: 120rpx;
}

.close {
  transform: rotate(90deg);
  margin-left: 30rpx;
}

.member-list-content {
  height: 70vh;
  box-sizing: border-box;
  overflow-y: auto;
}

.member-item {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 16rpx 40rpx;
}

.member-item-block {
  height: 200rpx;
}

.member-name {
  margin-left: 20rpx;
  font-size: 32rpx;
  padding-right: 40rpx;
  color: #333333;
  flex: 1;
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
}

.contact-item-icon {
  height: 84rpx;
  width: 84rpx;
  border-radius: 50%;
  text-align: center;
  line-height: 78rpx;
  font-size: 38rpx;
  color: #fff;
  background-color: #53c3f4;
}

.owner,
.manager {
  color: rgb(6, 155, 235);
  background-color: rgb(210, 229, 246);
  height: 40rpx;
  line-height: 40rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
  padding: 4rpx 8rpx;
  position: relative;
  right: 20rpx;
}
</style>
